package com.jinlejia.erp.ui.house;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.BeanKey;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.bean.BuildingBean;
import com.jinlejia.erp.bean.EstateBean;
import com.jinlejia.erp.bean.FloorBean;
import com.jinlejia.erp.bean.RoomBean;
import com.jinlejia.erp.bean.UnitBean;
import com.jinlejia.erp.databinding.ActivityHouseRecordAddressBinding;
import com.jinlejia.erp.ui.common.ChooseDialog;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.utils.DataFilter;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * \房源录入-物业地址
 */
public class HouseRecordAddressActivity extends AppCompatActivity {

    JSONObject jsonObject = new JSONObject();
    String type = "";

    private ProgressDialog progressDialog;
    private Http http;

    private ActivityHouseRecordAddressBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_house_record_address);

        binding.backBtn.setOnClickListener(this::onClick);
        binding.btNext.setOnClickListener(this::onClick);
        binding.houseName.setOnClickListener(this::onClick);
        binding.tvApply.setOnClickListener(this::onClick);

        http = new Http(this);
        binding.rgMain.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.sell_radio) {
                type = "shs";
            } else if (checkedId == R.id.rent_radio) {
                type = "rent";
            }
            jsonObject.put("type", type);
        });
        binding.tvApply.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG );
        binding.tvApply.getPaint().setAntiAlias(true);
        initView();

        progressDialog = new ProgressDialog(HouseRecordAddressActivity.this,"请稍后...");
    }

    private void initView() {
        //region 楼栋
        binding.noBuilding.setOnClickListener(v -> {
            if (TextUtils.isEmpty(binding.houseName.getText())){
                CustomToast.showToast(HouseRecordAddressActivity.this,"请选择楼盘",1500);
                return;
            }
            String name = String.valueOf(binding.houseName.getTag());
            http.queryBuildingList(name , beans -> {
                if (beans!=null){
                    showChooseDialog(binding.noBuilding, beans, object -> {
                        binding.noUnit.setText(null);
                        binding.noFloor.setText(null);
                        binding.noDoor.setText(null);
                        binding.totleFloor.setText(null);
                    });
                }
            });
        });
        //endregion

        //region 单元-楼栋号
        binding.noUnit.setOnClickListener(v -> {
            if (TextUtils.isEmpty(binding.noBuilding.getText())){
                CustomToast.showToast(HouseRecordAddressActivity.this,"请选择楼栋号",1500);
                return;
            }
            String key = String.valueOf(binding.noBuilding.getTag());
            http.queryEstateListByBuildingCode(key , beans -> {
                if (beans!=null){
                    showChooseDialog(binding.noUnit, beans, object -> {
                        binding.noFloor.setText(null);
                        binding.noDoor.setText(null);
                        binding.totleFloor.setText(null);
                    });
                }
            });
        });
        //endregion

        //region 楼层
        binding.noFloor.setOnClickListener(v -> {
            if (TextUtils.isEmpty(binding.noUnit.getText())){
                CustomToast.showToast(HouseRecordAddressActivity.this,"请选择单元号",1500);
                return;
            }
            String key = String.valueOf(binding.noUnit.getTag());
            http.queryFloorList(key, beans -> {
                if (beans!=null){
                    showChooseDialog(binding.noFloor, beans, object -> binding.noDoor.setText(null));
                }
            });
        });
        //endregion

        //region 门牌
        binding.noDoor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(binding.noFloor.getText())){
                    CustomToast.showToast(HouseRecordAddressActivity.this,"请选择楼层",1500);
                    return;
                }
                String key = String.valueOf(binding.noFloor.getTag());
                http.queryRoomList(key, new Http.QueryRoomListCallBack() {
                    @Override
                    public void onQueryRoomList(List<RoomBean> beans) {
                        if (beans!=null){
                            showChooseDialog(binding.noDoor, beans,null);
                        }
                    }
                });
            }
        });
        //endregion
        //region 总楼层
        binding.totleFloor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        //endregion
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.tvApply:
                Intent intent1 = new Intent(this,ApplyDictActivity.class);
                if (!TextUtils.isEmpty(binding.houseName.getText())){
                    intent1.putExtra("ishouse",0);
                    intent1.putExtra("houseName",binding.houseName.getText());
                    intent1.putExtra("housecode",binding.houseName.getTag().toString());
                    startActivity(intent1);
                }else{
                    intent1.putExtra("ishouse",1);
                    startActivity(intent1);
                }

                break;
            case R.id.house_name:
                Intent intent = new Intent(HouseRecordAddressActivity.this, SearchHouseActivity2.class);
                intent.putExtra("type", "select");
                startActivityForResult(intent, 101);
                break;
            case R.id.bt_next:
                //下一步
                jsonObject.put("buildingNo", binding.noBuilding.getText().toString());  //建筑号String
                jsonObject.put("houseNo", binding.noDoor.getText().toString());     //房号String
                jsonObject.put("unitNo", binding.noUnit.getText().toString());      //单元号String
                jsonObject.put("estate", binding.houseName.getText().toString());   //小区名String
                jsonObject.put("floor", binding.noFloor.getText().toString());      //楼层Integer
                jsonObject.put("allFloor", binding.totleFloor.getText().toString());//总楼层Integer
                String reCode = String.valueOf(binding.houseName.getTag());
                jsonObject.put("reCode",reCode);                            //楼盘编码String
                String buildingCode = String.valueOf(binding.noBuilding.getTag());
                jsonObject.put("buildingCode",buildingCode);                //座栋编码String
                String unitCode = String.valueOf(binding.noUnit.getTag());
                jsonObject.put("unitCode",unitCode);                        //单元编码String
                String roomCode = String.valueOf(binding.noDoor.getTag());
                jsonObject.put("roomCode",roomCode);                        //房间编码
                String floorCode = String.valueOf(binding.noFloor.getTag());
                jsonObject.put("floorCode",floorCode);   //楼层编码

                if(TextUtils.isEmpty(jsonObject.getString("type"))){
                    CustomToast.showToast(this,"请选择委托类型",1500);
                }else if(TextUtils.isEmpty(jsonObject.getString("estate"))){
                    CustomToast.showToast(this,"请选择楼盘",1500);
                }else if(TextUtils.isEmpty(jsonObject.getString("buildingNo"))){
                    CustomToast.showToast(this,"请选择楼栋号",1500);
                }else if(TextUtils.isEmpty(jsonObject.getString("houseNo"))){
                    CustomToast.showToast(this,"请选择门牌号",1500);
                }else if(TextUtils.isEmpty(jsonObject.getString("unitNo"))){
                    CustomToast.showToast(this,"请选择单元号",1500);
                }else if(TextUtils.isEmpty(jsonObject.getString("floor"))){
                    CustomToast.showToast(this,"请选择楼层",1500);
                }else if(TextUtils.isEmpty(jsonObject.getString("allFloor"))){
                    if (binding.totleFloor.isEnabled()){
                        CustomToast.showToast(this,"请输入总楼层",1500);
                    }else {
                        CustomToast.showToast(this,"请选择总楼层",1500);
                    }
                }else{
                    //查重
                    checkRepeat();
                }

                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 101) {
            EstateBean bean = data.getParcelableExtra("data");
            if (bean!=null){
                //当选中的楼盘信息和之前的不相同时
                if (!TextUtils.equals(binding.houseName.getText(),bean.toString())){
                    binding.houseName.setText(bean.toString()); //重新赋值楼盘信息
                    binding.houseName.setTag(bean.getReCode());
                    binding.noBuilding.setText(null); //清空楼栋信息
                    binding.noBuilding.setText(null);
                    binding.noUnit.setText(null); //清空单元信息
                    binding.noUnit.setTag(null);
                    binding.noFloor.setText(null); //清空楼层信息
                    binding.noFloor.setTag(null);
                    binding.noDoor.setText(null); //清空门牌信息
                    binding.noDoor.setTag(null);
                    binding.totleFloor.setText(null); //清空总楼层信息
                    binding.totleFloor.setTag(null);

                    if (bean.getArea()!=null&&!TextUtils.isEmpty(bean.getArea())){
                        jsonObject.put("area",bean.getArea());
                    }
                    if (bean.getCounty()!=null&&!TextUtils.isEmpty(bean.getCounty())) {
                        jsonObject.put("county", bean.getCounty());
                    }

                }
            }
        }
    }

    private void checkRepeat( ) {
        if( !progressDialog.isShowing())
        progressDialog.show();
        String url;
        if( type.equals("rent") ){
            url = ApiConfig.RENT_CHECK_REPEAT;
        }else{
            url = ApiConfig.SHS_CHECK_REPEAT;
        }
        OkHttpUtils.postString()
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (DataFilter.filter(HouseRecordAddressActivity.this, response)) {
                            Intent intent1 = new Intent(HouseRecordAddressActivity.this, HouseRecordInfoActivity.class);
                            intent1.putExtra("code", response.get("data").toString());
                            intent1.putExtra("type", type);
                            startActivity(intent1);
                        }
                    }
                });
    }


    //region http
    private static class Http{


        private final Context mContext;
        private Http(Context context){
            this.mContext = context;
        }

        //region 根据小区编码搜索座栋信息
        void queryBuildingList(String reCode, final QueryBuildingCallBack callBack){
            OkHttpUtils.get()
                    .url(ApiConfig.HOUSE_SOURCE_QUERY_BUILDING_LIST.concat(reCode))
                    .build()
                    .execute(new MapCallBack() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            CustomToast.showToast(mContext,"网络连接失败",1500);
                        }

                        @Override
                        public void onResponse(Map<String, Object> response, int id) {
                            if (showEmptyMessage(response))return;
                            if (DataFilter.filter(mContext,response)){
                                JSONObject data = JSON.parseObject(response.get("data").toString());
                                JSONArray list = data.getJSONArray("buildingList");
                                List<BuildingBean> beans = JSON.parseArray(list.toString(), BuildingBean.class);
                                callBack.onQueryBuilding(beans);
                            }
                        }
                    });
        }
        public interface QueryBuildingCallBack{
            void onQueryBuilding(List<BuildingBean> beans);
        }

        //endregion

        //region 根据座栋编号获取单元集合
        void queryEstateListByBuildingCode(String buildingCode,final UnitCallBack callBack){
            OkHttpUtils.get()
                    .url(ApiConfig.HOUSE_SOURCE_QUERY_UNIT_BY_BUILDING.concat(buildingCode))
                    .build()
                    .execute(new MapCallBack() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            CustomToast.showToast(mContext,"网络连接失败",1500);
                        }

                        @Override
                        public void onResponse(Map<String, Object> response, int id) {
                            if (showEmptyMessage(response))return;
                            if (DataFilter.filter(mContext,response)){
                                JSONObject data = JSON.parseObject(response.get("data").toString());
                                JSONArray list = data.getJSONArray("unitList");
                                List<UnitBean> beans = JSON.parseArray(list.toString(), UnitBean.class);
                                callBack.onUnitResult(beans);
                            }
                        }
                    });
        }

        public interface UnitCallBack{
            void onUnitResult(List<UnitBean> beans);
        }

        //endregion

        //region 根据单元编号获取楼层信息
        void queryFloorList(String unitCode,final QueryFloorListCallBack callBack){
            OkHttpUtils.get()
                    .url(ApiConfig.HOUSE_SOURCE_FLOOR_LIST.concat(unitCode))
                    .build()
                    .execute(new MapCallBack() {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(Map<String, Object> response, int id) {
                            if (showEmptyMessage(response))return;
                            if (DataFilter.filter(mContext,response)){
                                JSONObject data = JSON.parseObject(response.get("data").toString());
                                JSONArray list = data.getJSONArray("floorList");
                                List<FloorBean> beans = JSON.parseArray(list.toString(), FloorBean.class);
                                callBack.onFloorResult(beans);
                            }
                        }
                    });
        }

        public interface QueryFloorListCallBack{
            void onFloorResult(List<FloorBean> beans);
        }
        //endregion

        //region 根据楼层编码搜索房间列表
        void queryRoomList(String floorCode,final QueryRoomListCallBack callBack){
            OkHttpUtils.get()
                    .url(ApiConfig.HOUSE_SOURCE_QUERY_ROOM_LIST.concat(floorCode))
                    .build()
                    .execute(new MapCallBack() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            CustomToast.showToast(mContext,"网络连接失败",1500);
                        }

                        @Override
                        public void onResponse(Map<String, Object> response, int id) {
                            if (showEmptyMessage(response))return;
                            if (DataFilter.filter(mContext,response)){
                                JSONObject data = JSON.parseObject(response.get("data").toString());
                                JSONArray list = data.getJSONArray("roomList");
                                List<RoomBean> beans = JSON.parseArray(list.toString(), RoomBean.class);
                                callBack.onQueryRoomList(beans);
                            }
                        }
                    });
        }

        public interface QueryRoomListCallBack{
            void onQueryRoomList(List<RoomBean> beans);
        }
        //endregion


        private boolean showEmptyMessage(Map<String, Object> response){
            if ("501".equals(String.valueOf(response.get("code")))){
                if (response.get("message") != null)
                    CustomToast.showToast(mContext, response.get("message").toString(), 1500);
                return true;
            }
            return false;
        }

    }
    //endregion

    private ChooseDialog dialog;
    private void showChooseDialog(final TextView textView,List list,final ChooseDialog.ChooseListener listener){
        if (dialog!=null){
            dialog.dismiss();
            dialog = null;
        }
        if (list!=null && list.isEmpty()){
            CustomToast.showToast(this,"没有数据",1500);
            return;
        }
        dialog = new ChooseDialog(this,textView.getText().toString(),list);
        dialog.setListener(new ChooseDialog.ChooseListener() {
            @Override
            public void onChooseResult(Object object) {
                if (object instanceof BeanKey){
                    textView.setTag(((BeanKey) object).key());
                    if (listener!=null){
                        listener.onChooseResult(object);
                    }
                    if (object instanceof UnitBean){
                        UnitBean bean = (UnitBean) object;
                        if (TextUtils.isEmpty(bean.getAllFloor()) || "null".equalsIgnoreCase(bean.getAllFloor())){ //如果服务器没有总楼层
                            //1.提示用户进行输入楼层
                            binding.totleFloor.setEnabled(true);
                            binding.totleFloor.setHint("请输入总楼层");
                            binding.totleFloor.setText(null);
                        }else {
                            binding.totleFloor.setEnabled(false);
                            binding.totleFloor.setHint("请选择总楼层");
                            binding.totleFloor.setText(bean.getAllFloor());
                        }
                    }
                }
                textView.setText(String.valueOf(object));
                dialog = null;
            }
        });
        dialog.show();
    }

    @Override
    protected void onDestroy() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        super.onDestroy();
    }
}
